package com.ruoyi.file.service.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.ruoyi.file.service.OssPolicyService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Author：汤小洋
 * Date：2023-11-24 15:42
 * Description：<描述>
 */
@Service
public class OssPolicyServiceImpl implements OssPolicyService {

    @Resource
    private OSSClient ossClient;

    @Value("${spring.cloud.alicloud.oss.bucket}")
    private String bucket;

    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint;

    @Value("${spring.cloud.alicloud.access-key}")
    private String accessId;


    @SneakyThrows
    @Override
    public Map<String, String> policy() {
        String dir = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDateTime.now());
        long expireEndTime = System.currentTimeMillis() + 30 * 1000; // 过期时间30秒

        // 上传策略
        PolicyConditions policyConditions = new PolicyConditions();
        policyConditions.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000); // 设置上传文件的大小限制
        policyConditions.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir); // 设置上传文件的目录
        String postPolicy = ossClient.generatePostPolicy(new Date(expireEndTime), policyConditions); // 生成策略

        String encodedPolicy = BinaryUtil.toBase64String(postPolicy.getBytes("utf-8"));

        // 签名
        String postSignature = ossClient.calculatePostSignature(postPolicy);

        Map<String,String> map = new LinkedHashMap<>();
        map.put("host","https://" + bucket + "." + endpoint); // 上传地址
        map.put("dir",dir); // 上传目录
        map.put("expire",String.valueOf(expireEndTime)); // 过期时间
        map.put("accessId",accessId); // accessId
        map.put("policy",encodedPolicy); // 策略
        map.put("signature",postSignature); // 签名

        return map;
    }
}
